import React from 'react';
import './newProgress3.scss';
import {
    HashRouter as Router,
    Route,
    Link
} from 'react-router-dom';

import utils from '../../../utils/utils';
import cookie from 'react-cookies';
import BMap from 'BMap';
import moment from 'moment';
import BreadcrumbNav from '../../../component/breadcrumb/breadcrumb.js';
import {Form, List, Row , Col, Button,Table,Card, Input,Upload,message,Radio, Checkbox,Select ,Cascader ,InputNumber,Modal } from 'antd';
import BarrierGate from '../../../component/progress/progress.js';
import NextMenu from "../../../component/nextMenu/nextMenu"
import { EditOutlined, DeleteOutlined ,SettingOutlined,LoadingOutlined, PlusOutlined ,UploadOutlined,PlusCircleFilled} from '@ant-design/icons';
import { categoryList,eqModelList,getModelByEq,getSaasInfo} from '../../../api/deviceLibrary'
import { getCustomerMenu } from '../../../api/hardwareCenter'
import { fileUpload } from "../../../api/extra";
const { Column } = Table;
const { Option } = Select; 
const CheckboxGroup = Checkbox.Group

class newProgress3 extends React.Component {
  
  selfForm = React.createRef();
      constructor(props){
        super(props);
        this.state = {
            loading:false,
            saasType: props.OptionThirdStep.saasType || 1,
            otherType: props.OptionThirdStep.otherType || [],
            activeUlId:'133',
            data: props.OptionThirdStep.data || [],
            dataSource : props.OptionThirdStep.dataSource || [],
            list: props.OptionThirdStep.list || [],
            list_info: props.OptionThirdStep.list_info || [
              {}
            ],
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            device:  props.OptionThirdStep.device || '',
            normSet: props.OptionThirdStep.normSet || false,
            normSetedit: props.OptionThirdStep.normSetedit || false,
            activeindex:  props.OptionThirdStep.activeindex ||  '',
            activeindexedit:  props.OptionThirdStep.activeindexedit ||  '',
            spec_info:  props.OptionThirdStep. spec_info || [],
            showtypes:  props.OptionThirdStep.showtypes || [],
            type:  props.OptionThirdStep.type || '',
            guige:  props.OptionThirdStep.guige || '',
            modelValue:  props.OptionThirdStep.modelValue || "",
            fileList:  props.OptionThirdStep.fileList || [],
            self_info:  props.OptionThirdStep.self_info || [],
            isPub:false,
            saas_ac_is_limit: props.OptionThirdStep.saas_ac_is_limit ||'2',
            ah_list3:props.OptionThirdStep.ah_list3 || '',
            otherType:[],
            ah_list_tmp: [
              {
                  one: {
                      isChecked: false,
                      value:  '一级1',
                  },
                  lt: [{
                      id: 1,
                      label: '二级1',
                      value: '二级1',
                  },{
                      id: 2,
                      label: '二级2',
                      value: '二级2',
                  },],
                  ck_lt: [],
              },{
                  one: {
                      isChecked: false,
                      value:  '一级2',
                  },
                  lt: [{
                      id: 1,
                      label: '二级1',
                      value: '二级1',
                  },{
                      id: 2,
                      label: '二级2',
                      value: '二级2',
                  },],
                  ck_lt: [],
                  editName:'',
                
              }
          ],

        }}
    

    componentDidMount() {
      // 获取权限菜单
      this.getCustomerMenu2Free()
      // 获取设备列表
      this.categoryList()
        this.setState({
            activeUlId:'1'
            
        },() => {
            console.log(this.state.activeUlId)
            console.log('this.props',this.props)
        })
       
    }
    // 获取可选菜单
    getCustomerMenu2Free() {
      let _this = this;
      let post_data = {
          auth_token:cookie.load('station_console_setting_web_login').auth_token,
          type:'2'
      }

      getCustomerMenu(post_data).then(res => {
          if(res.code == 0){
              let mt = res.data.menu;
              
              console.log('mt',mt)
              console.log('111111111',this.state.menuid2)
              mt&&mt.length>0&&mt.forEach((val, ind) => {
                  val.ck_lt = [];
                  if(this.state.menuid2){
                      this.state.menuid2.map((e,i)=>{
                          if(val.id == e){
                              console.log('同')
                              val.ck_lt.push(e)
                          }
                          if(val.children && val.children.length > 0){
                              val.children.map((item,index)=>{
                                  if(item.id == e){
                                      console.log('同子')
                                      val.ck_lt.push(e)
                                  }
                              })
                          }
                      })
                  }
              });
              _this.setState({
                  ah_list3: mt,
                  menuid2:res.data.menu_id?res.data.menu_id.split(','):''
              })
          }
      })
    }
    // 设备列表
    categoryList=()=>{
      let post_data = {
          'auth_token': cookie.load('station_console_setting_web_login').auth_token,
      }
      categoryList(post_data).then(res=>{
        res.data.list.map((item,index)=>{
          item.value=item.name
          item.label=item.name
          item.children=item.eq_list 
          item.children.map((el,i)=>{
              el.value=el.id
              el.label=el.cate_name
              el.state=el.state
          })  
        })
          this.setState({
              list:res.data.list
          },()=>{
            console.log(this.state.list)
          })
      })
  }
    // 取消
    cancel = () => {
      let _this=this
      console.log('cancel')
      window.location.href='/index/hardwareCenter/programConfig'
    
    }
    // 上一步
    prev2 = () => {
      // this.props.history.push({pathname:'/addNewPro2'})
    }
   
    toPublish = () => {
      console.log('发布')
     
        let { newPositionName, industryCreate, jobNameChange, jobType, ah_list3 } = this.state;
        let otherType = new Array();
        let ah_check_name = new Array();

        ah_list3.map((val, ind) => {

            if(val.ck_lt && val.ck_lt.length>0){
                otherType.push(val.ck_lt);
                ah_check_name.push(val.menu_name)
            }
           
        })
        let a = otherType.flat(1)
        

        this.setState({
            otherType:a,
            ah_check_name,
        },()=>{
            console.log('修改',this.state.otherType)
        })
      this.setState({isPub:true},()=>{
        this.props.callback(this.state)
      })
      
      
    }
   

    getBase64 = (file) => {
      console.log("getbase64", file);
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    };
    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async (index,file) => {
      console.log(file);
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
      }

      this.setState({
        previewImage: file.url || file.preview,
        previewVisible: true,
        previewTitle:
          file.name || file.url.substring(file.url.lastIndexOf("/") + 1),
      });
    };
    uploadHeadImg = (index,info) => {
      const { fileList,self_info } = this.state;
      
      let post_data = {
        auth_token: cookie.load("station_console_setting_web_login").auth_token,
        file: info.file,
        file_type: 1,
      };
      console.log(post_data);
      fileUpload(post_data).then((res) => {
        console.log(res);
        self_info[index].fileList.push({
          url: res.data.full_url,
          status: "done",
          uid: res.data.attach_id,
        });
  
        this.setState(
          {
            self_info,
          },
          () => {
            console.log(self_info);
          }
        );
      });
    };
    // remove-file
    removefile = (index,file) => {
      const {self_info} = this.state
     
      self_info[index].fileList && 
      self_info[index].fileList.forEach((item, i) => {
          if (file.uid === item.uid) {
            self_info[index].fileList.splice(i, 1);
          }
      });
      this.setState({
        self_info
      })
    };
    onChangeSaas = e => {
      if(e.target.value == 1){
        this.setState({
          saas_ac_is_limit:2,
          saasType:e.target.value,
        })
      }else{
        this.setState({
          saasType:e.target.value,
          saas_ac_is_limit:1
        },()=>{
          console.log('radio checked', this.state.saasType);
        })
      }
      // setValue(e.target.value);
     
    };

    onChange2 = val => {
   
      this.setState({
        otherType:val
      },()=>{
        console.log('radio checked', this.state.otherType);
      })
    };

    // 点击添加设备
    handleAdd = () => {
      const {list_info} = this.state
      list_info.push({
        eq_type: '' , 
        eq_id: '',
        eq_sku_id: [{
          spu_id:'',
          spec_key:[],
          spec_value:[]
        }],
        setOk: false,
        eq_count:'',
        eq_name1:''
        
      })
      this.setState({
          list_info 
      },()=>{
        console.log(list_info)
      })
    
    }
    // 选择设备
    choseDevice = (index,value,selectedOptions)=>{ 
      console.log(value)
      const { list_info } = this.state;
      
      list_info[index].eq_name1=value[0]
      list_info[index].eq_id =value[1]; 
      list_info[index].eq_type ='1'; 
      list_info[index].eq_name = selectedOptions[1].label; 
      list_info[index].setOk = false; 
      this.setState({
        list_info,
      })
    }

    // 数量设置
    setNumber = (index,value) => {
      const { list_info, } = this.state;
      list_info[index].eq_count=value
      this.setState({
        list_info
      })
    }

    // // 删除
    handleDelete = (el) => {
      const { list_info} = this.state
      list_info.splice(el,1)
      this.setState({
          list_info,
         
      },()=>{
        console.log(this.state.list_info)
      })
    }
    
    // 点击编辑
    handleEdit = (index) => {
      this.setState({
        normSetedit:true,
        activeindexedit:index
      },()=>{
        console.log('activeindex',this.state.activeindex)
        console.log('activeindexedit',this.state.activeindexedit)
      })
    }

    // 点击对应的规格配置
    deviceSet = (item,index) => {
      if(!item.eq_id){
        message.error('请先选择对应设备')
        return
      }
      
      this.setState({
        normSet: true,
        activeindex: index,
      })
      
    }
   
    // 点击相关属性设置
    typeSet = (e) => {
      const {activeindex,list_info} = this.state
    }

    setGuige = (index,e) => {
      const { list_info } = this.state
      list_info[index].guige = e.target.value;
      this.setState({
        list_info
      })
    }
    modelll = (index,e) => {
      const { list_info } = this.state
      list_info[index].eq_sku_id[0].eq_model = e.target.value;
      this.setState({
        list_info
      })
    }

    childSetState = (key, value) => {
      this.setState({
        [key]: value
      })
    }
    // 新增
    handleListInfo = (data) => {
      const { list_info, activeindex } = this.state
      list_info.splice(activeindex, 1, data)
      this.setState({
        list_info,
      })
    }
    // 编辑
    handleListInfoedit = (data) => {
      const { list_info, activeindexedit } = this.state
      list_info.splice(activeindexedit, 1, data)
      this.setState({
        list_info,
      })
    }

    // 添加自有设备
    // 点击添加设备
    handleAddSelf = () => {
      const {self_info} = this.state
      self_info.push({
        eq_type:'2',
        eq_brand_name:'',
        fileList:[],
        eq_count:'',
        eq_name:''
      })
      this.setState({
        self_info 
      },()=>{
        console.log(this.state.self_info)
      })
    
    }
    delSelfDevice = (el) =>{
      const { self_info} = this.state
      self_info.splice(el,1)
      this.setState({
          self_info
      })
    }

    // 
    onCheckAllChange(ind, e) {
      let _this = this;
      let flag = e.target.checked;
      let { ah_list3 } = _this.state;
      
  
      if(flag){
          if(!ah_list3[ind].ck_lt.includes(ah_list3[ind].id)){
              ah_list3[ind].ck_lt.push(ah_list3[ind].id);
          }
      }else {
          if(ah_list3[ind].ck_lt.includes(ah_list3[ind].id)){
              ah_list3[ind].ck_lt.splice(ah_list3[ind].ck_lt.indexOf(ah_list3[ind].id), 1);
          }
      }

      if(ah_list3[ind].children && ah_list3[ind].children.length > 0){
          let ah_list3_children = ah_list3[ind].children;
          ah_list3_children.map((val, index) => {
              if(1 != val.can_not_change){
                  if(flag){
                      val.default_selected = '1';
                      if(!ah_list3[ind].ck_lt.includes(val.id)){
                          ah_list3[ind].ck_lt.push(val.id);
                      }
                  }else {
                      val.default_selected = '0';
                      ah_list3[ind].ck_lt.splice(ah_list3[ind].ck_lt.indexOf(val.id), 1);
                  }
              }
          })
      }

      ah_list3[ind].default_selected = flag ? 1 : 0;
      _this.setState({
          ah_list3,
      })
  }
  // kexuan
  onChangeget(ind, list) {        
    let _this = this;
    let { ah_list3 } = _this.state;

    ah_list3[ind].ck_lt = list;

    if(ah_list3[ind].children){
        ah_list3[ind].children.map((val, ind) => {
            if(list){
                if(list.includes(val.id)){
                    val.default_selected = 1;
                }else {
                    val.default_selected = 0;
                }
            }
        })
    }

    if(list.length > 0){
        ah_list3[ind].default_selected = 1;

        if(!ah_list3[ind].ck_lt.includes(ah_list3[ind].id)){
            ah_list3[ind].ck_lt.push(ah_list3[ind].id);
        }
    }else {
        ah_list3[ind].default_selected = 0;
    }
    _this.setState({
        ah_list3: ah_list3
    })
}
  


    render() {
        const { 
          activeindex,
          activeUlId,
          showtypes,
          type,
          dataSource,
          columns,
          loading,
           imageUrl,
          saasType,
          otherType,
          list,
          list_info,
          device,
          normSet,
          normSetedit,
          spec_info,
          previewVisible,
          previewTitle,
          previewImage,
          modelValue,
          fileList,
          self_info,
          saas_ac_is_limit,
          ah_list3,
          activeindexedit
        
        } = this.state;
        const { prev2 } = this.props;
        const uploadButton = (
          <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
          </div>
        );
    
        return (
          <Router>
          <div className="addNewPro3" id="ContentMainList">
             
          
              <Row className="steps-action">
                  <Col span={24}>
                      <div className="tipss">
                          <span className="blue"></span>
                          <span>项目设备配备</span>
                          <div className="addDevice" onClick={this.handleAdd.bind(this)}>
                              <span className="add_times">添加设备</span>
                          </div>
                      </div>
                      <div className='table_header'>
                        
                        {/* 原来的 */}
                        <table border="1"  cellSpacing="0" width="1000px" borderColor=" #fff" align="center" margin="0px" >
                            
                            <tr height="42px" >
                              <td width="35px"  align="center">序号</td>
                              <td width="125px" align="center">设备</td>
                              <td width="60px" align="center">数量</td>
                              <td width="150px" align="center">规格</td>
                              <td width="100px" align="center">操作</td>
                            </tr>
                            
                            <tbody >
                                {list_info.map((item,index) =>(
                                    <tr  key={index}>
                                        <td align="center" >
                                            <span >{index+1}</span>
                                        </td>
                                        <td align="center" >
                                            
                                          <Cascader disabled={item.setOk} options={list} value={[item.eq_name1,item.eq_id]}  onChange={this.choseDevice.bind(this,index)} placeholder="请选择设备类型" />
                                        </td>
                                        <td align="center">
                                          <InputNumber min={1} max={10} value={item.eq_count} onChange={this.setNumber.bind(this,index)} />
                                        </td>
                                        <td align="center" >
                                    {item.setOk?
                                    // <span>{activeDevice}---{showtypes}</span>
                                    <Row>
                                      <Col span={12}>
                                      <Input style={{display:'inline-block'}} disabled={true} value={item.eq_sku_id[0]&&item.eq_sku_id[0].eq_model} onChange={this.modelll.bind(this,index)}/>
                                      </Col>
                                      <Col span={12}>
                                      <Input style={{display:'inline-block'}} disabled={true} value={item.guige} onChange={this.setGuige.bind(this,index)}/>
                                      </Col>
                                      
                                    </Row>
                                    // <span>{list_info.guige}</span>
                                    :
                                    <Button onClick={this.deviceSet.bind(this,item,index)} type="text"  style={{color:'#2F3CF2'}}>规格配置<SettingOutlined /></Button>}
                                        </td>
                                        <td  style={{display:'flex',justifyContent:'center',alignItems:'center'}} >
                                            
                                          {item.setOk ? <div style={{marginRight:'10px'}} onClick={this.handleEdit.bind(this,index)}><EditOutlined/></div>:null}
                                            <div style={{marginRight:'10px'}} onClick={this.handleDelete.bind(this,index)}><DeleteOutlined/></div>
                                            
                                            
                                        </td>
                                    </tr>
                                ))} 
                            </tbody>
                        </table>
                      </div>
                      
                     
                      <div className="tipss" style={{ marginTop:'80px'}} >
                          <span className="blue"></span>
                          <span>站台自有设备</span>
                          <div className="addDevice" onClick={this.handleAddSelf.bind(this)}>
                              <span className="add_times">添加设备</span>
                          </div>
                      </div>
                      {
                        self_info&&self_info.map((item,index)=>(
                        <Card size="small" style={{ width: 800 }} key={index}>
                          <Row style={{margin:'20px'}}>
                              <Col span={10} >
                                  <span>设备名称：</span>
                                  <Input  
                                    style={{width:'220px'}}
                                    value={item.eq_name}
                                    onChange={(e) => {
                                      const { self_info } = this.state
                                      self_info[index].eq_name = e.currentTarget.value;
                                      this.setState({ self_info });
                                    }}
                                  />
                              </Col>
                              <Col span={10}>
                              <span>设备数量：</span>
                                  <Input 
                                    value={item.eq_count}
                                    onChange={(e) => {
                                      const { self_info } = this.state
                                      self_info[index].eq_count = e.currentTarget.value;
                                      this.setState({ self_info });
                                    }}
                                    style={{width:'220px'}}/>
                              </Col>
                               <Col span={4}>
                                <span onClick={this.delSelfDevice.bind(this,index)}><DeleteOutlined /></span>
                              </Col>
                            </Row>
                            <Row style={{margin:'20px'}}>
                              <Col span={24} >
                                  <span>品牌：</span>
                                  <Input 
                                    value={item.eq_brand_name}
                                    onChange={(e) => {
                                      const { self_info } = this.state
                                      self_info[index].eq_brand_name = e.currentTarget.value;
                                      this.setState({ self_info });
                                    }}
                                   style={{width:'220px'}}/>
                              </Col>
                            </Row>
                            <Row style={{margin:'20px'}}>
                              <Col span={24} >
                                  <span>照片采集：</span>
                                  <div style={{marginLeft:'80px'}}>
                                  <Upload
                                      // action={`${process.env.API_URL}/internal_public/attach/fileUpload`}
                                      customRequest={this.uploadHeadImg.bind(this,index)}
                                      listType="picture-card"
                                      showUploadList={{ showRemoveIcon: true }}
                                      fileList={item.fileList}
                                      onRemove={this.removefile.bind(this,index)}   
                                      onPreview={this.handlePreview.bind(this,index)}
                                      // onChange={this.handleChange.bind(this)}
                                    >
                                      {fileList.length >= 10 ? null : uploadButton}
                                    </Upload>
                                  </div>
                                  <span className="spaninner">（务必上传设备铭牌图片）</span>
                              </Col>
                            </Row>
                          
                        </Card>
                        ))
                      }
                     
                      <div className="tipss" style={{ marginTop:'80px'}} >
                          <span className="blue"></span>
                          <span>SAAS服务配置</span>
                      </div>
                      <div className="saasType">
                        <span>账号数：</span>
                        <Radio.Group onChange={this.onChangeSaas.bind()} value={saasType}>
                          <Radio value={1}>不限</Radio>
                          <Radio value={10}>10</Radio>
                          <Radio value={20}>20</Radio>
                          <Radio value={50}>50</Radio>
                        </Radio.Group>
                      </div>
                      <div className="saasType">
                        <span>软件功能：</span>
                        <span>基础功能（必选）</span>
                      </div>
                      <div className="saasType" >
                        <span>其他功能：</span>
                        <div className="list">
                            { ah_list3&&ah_list3.map((val, ind) => (
                            <div className="ay-wrap" key={ ind }>
                                    <Checkbox className="ck-one" onChange={this.onCheckAllChange.bind(this, ind)} >{ val.menu_name }</Checkbox>
                                    { val.children ?
                                        <CheckboxGroup className="ck-two" value={val.ck_lt}   onChange={this.onChangeget.bind(this, ind) }>
                                            { val.children.map((vl, index) => (
                                                <Checkbox   value={ vl.id }  >{ vl.menu_name }</Checkbox>
                                            ))}
                                        </CheckboxGroup> : null 
                                    }
                                </div>
                            ))}

                        </div>
                        </div>
                        {/* <Checkbox.Group style={{ width: '80%' }} onChange={this.onChange2.bind()} 
                        
                        defaultValue={otherType}>
                          <Row>
                            <Col span={8}>
                              <Checkbox value="1">监控管理 - 监控管理</Checkbox>
                            </Col>
                            <Col span={8}>
                              <Checkbox value="2">库存管理 - 库存管理</Checkbox>
                            </Col>
                            <Col span={8}>
                              <Checkbox value="3">一级功能模块 - 二级功能模块</Checkbox>
                            </Col>
                            
                          </Row>
                        </Checkbox.Group> */}
                        
                  </Col>
              </Row>
              <Row>
                <Col span={24} className="footer">
                <Button type="primary" onClick={this.cancel.bind(this)} style={{ display: 'inline-block', width: '120px' ,marginRight:'12px'}}>
                      取消
                  </Button>
                  <Button type="primary" onClick={()=>prev2(this.state)} style={{ display: 'inline-block', width: '120px' ,marginRight:'12px'}}>
                     上一步
                  </Button>
                  <Button type="primary" onClick={this.toPublish.bind(this,this.state)} style={{ display: 'inline-block', width: '120px' ,marginRight:'12px'}} >
                    创建
                  </Button>
                </Col>
              </Row>
              {
                normSet && 
                <ModelModal
                  childSetState={this.childSetState}
                  normSet={normSet}
                  listData={list_info[activeindex]}
                  handleListInfo={this.handleListInfo}
                />
              }
              {
                normSetedit && 
                <ModelModaledit
                  childSetState={this.childSetState}
                  normSetedit={normSetedit}
                  activeindexedit={activeindexedit}
                  listData={list_info[activeindexedit]}
                  handleListInfoedit={this.handleListInfoedit}
                />
              }
          </div>
          <Modal
            visible={previewVisible}
            title={previewTitle}
            footer={null}
            onCancel={this.handleCancel.bind(this)}
          >
            <img alt="example" style={{ width: "100%" }} src={previewImage} />
          </Modal>
      </Router>
        )
    }
}

export default newProgress3;

// 新建的dialog
class ModelModal extends React.PureComponent { 
  cpmForm = React.createRef();
  
  constructor(props) {
    super(props)
    this.state = {
      normOption: [],
      modelValue: "",
      key: Math.random().toString().slice(3,6),
    }
  }

  // 验证是否是中文
  CheckChinese=(str)=> {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    return reg.test(str)
  }

  // 完成规格配置
  saveNormSet =() => {
    const { modelValue } = this.state;
    const { listData, handleListInfo, childSetState ,activeindex} = this.props;

    const newObj = this.cpmForm.current.getFieldsValue()
    const clobj = JSON.parse(JSON.stringify(newObj))

    if(!modelValue){
      message.error('请选择对应设备型号！')
      return
    }
    
    for (let key in newObj) {
      if(newObj[key] == undefined){
          message.warn(`请选择${key}规格`)
          return
      }
    }
    const copyListData = JSON.parse(JSON.stringify(listData))

    !copyListData.eq_sku_id && (copyListData.eq_sku_id = [])
    !copyListData.eq_sku_id[0] && (copyListData.eq_sku_id[0] = {})
    copyListData.eq_sku_id[0].spu_id = modelValue
    copyListData.setOk = true;
    !copyListData.eq_sku_id[0].spec_key && (copyListData.eq_sku_id[0].spec_key=[])
    !copyListData.eq_sku_id[0].spec_value && (copyListData.eq_sku_id[0].spec_value=[])
    copyListData.guige = []
    
    for (let key in clobj) {
        if (this.CheckChinese(key)) {
          copyListData.eq_sku_id[0].spec_key.push(key)
          copyListData.eq_sku_id[0].spec_value.push(clobj[key])
          copyListData.guige.push(clobj[key])
        }
    }
    // 统计所有的汉字key值
    // let oldArr = []
    // for (let index = 0; index < copyListData.spec_info.length; index++) {
    //   oldArr.push(copyListData.spec_info[index].spec_key)
    // }
    
    // copyListData.eq_sku_id[0].spec_key = [...new Set(oldArr)]
    let spuId =  copyListData.eq_sku_id[0].spu_id
    console.log(this.state.normOption,spuId)
    let suitItem =this.state.normOption.filter((item,index)=>{
      if(item.spu_id == spuId){
        return  item
      }
    })
    console.log('eq_model',suitItem)
    copyListData.eq_sku_id[0].eq_model =  suitItem[0].eq_model&&suitItem[0].eq_model
    copyListData.eq_brand_name =  suitItem[0].brand_name
    console.log('要提交的copy listdata',copyListData)
    handleListInfo(copyListData);
    childSetState("normSet", false)
  }

  request = () => {
    const { listData } = this.props;
    const { modelValue, key } = this.state;
    const post_data = {
      'auth_token': cookie.load('station_console_setting_web_login').auth_token,
      'id': listData.eq_id,
      'is_offer':1
    }
    getModelByEq(post_data).then(res => {
      if(res.code == 0){
        const normOption = res.data.eq_info;
        const defaultOption = {};
        if (listData.eq_sku_id && listData.eq_sku_id[0] && listData.eq_sku_id[0].spec_value) {
          const data = normOption.find(item => item.spu_id === (modelValue || (normOption[0] && normOption[0].spu_id)));
          (data && data.spec_info || []).forEach((item, index) => {
            defaultOption[`${item.spec_key}`] = listData.eq_sku_id[0].spec_value[index]
          })
        }
        
        this.cpmForm.current.setFieldsValue({
          spu_id:(listData.eq_sku_id && listData.eq_sku_id[0].spu_id) || (normOption[0] && normOption[0].spu_id),
          ...defaultOption
        })
        this.setState({
          modelValue: (listData.eq_sku_id && listData.eq_sku_id[0].spu_id) || normOption[0].spu_id,
          normOption: normOption,
        })
      }
    })
  }

  componentDidMount() {
    this.request()
  }  

  componentDidUpdate() {
    
  }

  render() {
    const {
      normSet,
      listData,
      childSetState,
      handleListInfo,
    } = this.props;

    const { normOption, modelValue, key } = this. state;

    const normOptionDom = () => {
      if (!normOption.length) return;
      const data = normOption.find(item => item.spu_id === modelValue);
      return (data && data.spec_info || []).map((item, index) => (
        <Form.Item
          key={key}
          name={`${item.spec_key}`}
          label="设备规格 "
          rules={[
            {
              required: true,
              message: `请选择${item.spec_key}`,
            },
          ]}
        >
          <Radio.Group
            label={data.spec_key}
            value={data.setOk ? listData.guige[index] : ""}
            >
            {
              item.spec_value &&
              item.spec_value.map((ii, ind)=> (
                  <Radio key={ind} value={ii} style={{marginRight:8}}>{ii}</Radio>
              ))
            }
          </Radio.Group>
        </Form.Item>
      ))
          
    }
   
    return (
      <Modal title="设备规格选择" visible={normSet} onOk={this.saveNormSet} onCancel={()=>{childSetState("normSet", false)}}>
        <Row>
          <Form 
            ref={this.cpmForm}
            initialValues={{
              activeDevice: listData.eq_name,
            }}
          >
            <Col span={12}>
                <Form.Item
                  key={"activeDevice"}
                  name="activeDevice"
                  label="设备种类："
                  style={{backgroundColor:'#fff'}}
                >
                    <Input style={{display:'inline-block' ,width:'120px'}}/>
                </Form.Item>
            </Col>   
            <Col span={12}>
              <Form.Item
                key={"spu_id"}
                name="spu_id"
                label="设备型号："
                rules={[{ required: true, message: '请选择设备型号' }]}
                style={{width:'150px',backgroundColor:'#fff'}}
                initialValue={modelValue || (normOption[0] ? normOption[0].spu_id + "" : "")}
                >
                  <Select
                    onChange={(val) => {
                      console.log('valll',val)
                      // const copyListData = JSON.parse(JSON.stringify(listData))
                      const copyListData = listData
                      copyListData.eq_sku_id = []
                      handleListInfo(copyListData)
                      this.setState({
                        modelValue: val,
                      })
                    }}
                    style={{minWidth: 120}}
                    >
                    {
                      normOption.length &&
                      normOption.map(item =>( 
                        <Option key={item.spu_id} value={item.spu_id}>{item.eq_model}</Option>
                      ))
                    }
                  </Select>
              </Form.Item>
            </Col>
            {/* <Col span={12}>
              <span>设备型号：</span>
              <Select onChange={this.setModeltype.bind(this)}  style={{ width: 120 }} >
                {set_list&&set_list.map((item,index)=>( 
                  <Option value={item.spu_id}>{item.eq_model}</Option>
                ))}
              </Select>
            </Col> */}
            <Col span={24}>
              {
                normOption[0] &&
                normOption[0].spec_info &&
                normOption[0].spec_info.length &&
                modelValue && 
                normOptionDom()
              }
            </Col>
          </Form>
        </Row>
      </Modal>
    )
  }
}

// 编辑的dialog
class ModelModaledit extends React.PureComponent { 
  cpmFormedit = React.createRef();
  
  constructor(props) {
    super(props)
    this.state = {
      normOption: [],
      modelValue: "",
      key: Math.random().toString().slice(3,6),
    }
  }

  // 验证是否是中文
  CheckChinese=(str)=> {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    return reg.test(str)
  }

  // 完成规格配置
  saveNormSetedit =() => {
    const { modelValue } = this.state;
    const { listData, handleListInfoedit, childSetState ,activeindexedit} = this.props;
    console.log('getttttttttttttttttttttFIELDS',this.cpmFormedit.current.getFieldsValue())
    //this.cpmFormedit.current.resetFields()
    console.log('listdata',listData)
    const newObj = this.cpmFormedit.current.getFieldsValue()

    // let newObj = {
    //   activeDevice:newObjls.activeDevice,
    //   spu_id:newObjls.spu_id
    // }
    console.log(newObj)
    const clobj = JSON.parse(JSON.stringify(newObj))

    if(!modelValue){
      message.error('请选择对应设备型号！')
      return
    }
    
    for (let key in newObj) {
      if(newObj[key] == undefined){
          message.warn(`请选择${key}规格`)
          return
      }
    }
    console.log('list2222',listData)
    const copyListData = listData
    console.log('copylistData',copyListData)
    !copyListData.eq_sku_id && (copyListData.eq_sku_id = [])
    !copyListData.eq_sku_id[0] && (copyListData.eq_sku_id[0] = {})
    copyListData.eq_sku_id[0].spu_id = modelValue
    copyListData.setOk = true;
    !copyListData.eq_sku_id[0].spec_key && (copyListData.eq_sku_id[0].spec_key=[])
    !copyListData.eq_sku_id[0].spec_value && (copyListData.eq_sku_id[0].spec_value=[])
    copyListData.guige = []
    copyListData.eq_sku_id[0].spec_key=[]
    copyListData.eq_sku_id[0].spec_value=[]
    console.log(copyListData)
    for (let key in clobj) {
        if (this.CheckChinese(key)) {
          copyListData.eq_sku_id[0].spec_key.push(key)
          copyListData.eq_sku_id[0].spec_value.push(clobj[key])
          copyListData.guige.push(clobj[key])
        }
    }
    // 统计所有的汉字key值
    // let oldArr = []
    // for (let index = 0; index < copyListData.spec_info.length; index++) {
    //   oldArr.push(copyListData.spec_info[index].spec_key)
    // }
    
    // copyListData.eq_sku_id[0].spec_key = [...new Set(oldArr)]
    let spuId =  copyListData.eq_sku_id[0].spu_id
    console.log(this.state.normOption,spuId)
    let suitItem =this.state.normOption.filter((item,index)=>{
      if(item.spu_id == spuId){
        return  item
      }
    })
    console.log('eq_model',suitItem)
    copyListData.eq_sku_id[0].eq_model =  suitItem[0].eq_model&&suitItem[0].eq_model
    copyListData.eq_brand_name =  suitItem[0].brand_name
    console.log('要提交的copy listdata',copyListData)
    handleListInfoedit(copyListData);
    childSetState("normSetedit", false)
  }

  request = () => {
    const { listData } = this.props;
    const { modelValue, key } = this.state;
    const post_data = {
      'auth_token': cookie.load('station_console_setting_web_login').auth_token,
      'id': listData.eq_id,
      'is_offer':1
    }
    getModelByEq(post_data).then(res => {
      if(res.code == 0){
        const normOption = res.data.eq_info;
        const defaultOption = {};
        if (listData.eq_sku_id && listData.eq_sku_id[0] && listData.eq_sku_id[0].spec_value) {
          const data = normOption.find(item => item.spu_id === (modelValue || (normOption[0] && normOption[0].spu_id)));
          (data && data.spec_info || []).forEach((item, index) => {
            defaultOption[`${item.spec_key}`] = listData.eq_sku_id[0].spec_value[index]
          })
        }
        
        this.cpmFormedit.current.setFieldsValue({
          spu_id:(listData.eq_sku_id && listData.eq_sku_id[0].spu_id) || (normOption[0] && normOption[0].spu_id),
          ...defaultOption
        })
        this.setState({
          modelValue: (listData.eq_sku_id && listData.eq_sku_id[0].spu_id) || normOption[0].spu_id,
          normOption: normOption,
        })
      }
    })
  }

  componentDidMount() {
    this.request()
  }  

  componentDidUpdate() {
    
  }

  render() {
    const {
      normSetedit,
      listData,
      childSetState,
      handleListInfoedit,
    } = this.props;

    const { normOption, modelValue, key } = this. state;

    const normOptionDom = () => {
      if (!normOption.length) return;
      const data = normOption.find(item => item.spu_id === modelValue);
      console.log('dataaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',data)
      return (data && data.spec_info || []).map((item, index) => (
        <Form.Item
          key={key}
          name={`${item.spec_key}`}
          label={`${item.spec_key}`}
          rules={[
            {
              required: true,
              message: `请选择${item.spec_key}`,
            },
          ]}
        >
          <Radio.Group
            label={data.spec_key}
            value={data.setOk ? listData.guige[index] : ""}
            >
            {
              item.spec_value &&
              item.spec_value.map((ii, ind)=> (
                  <Radio key={ind} value={ii} style={{marginRight:8}}>{ii}</Radio>
              ))
            }
          </Radio.Group>
        </Form.Item>
      ))
          
    }
   
    return (
      <Modal title="设备规格选择" visible={normSetedit} onOk={this.saveNormSetedit} onCancel={()=>{childSetState("normSetedit", false)}}>
        <Row>
          <Form 
            ref={this.cpmFormedit}
            initialValues={{
              activeDevice: listData.eq_name,
            }}
          >
            <Col span={12}>
                <Form.Item
                  key={"activeDevice"}
                  name="activeDevice"
                  label="设备种类："
                  style={{backgroundColor:'#fff'}}
                >
                    <Input style={{display:'inline-block' ,width:'120px'}}/>
                </Form.Item>
            </Col>   
            <Col span={12}>
              <Form.Item
                key={"spu_id"}
                name="spu_id"
                label="设备型号："
                rules={[{ required: true, message: '请选择设备型号' }]}
                style={{width:'150px',backgroundColor:'#fff'}}
                initialValue={modelValue || (normOption[0] ? normOption[0].spu_id + "" : "")}
                >
                  <Select
                    onChange={(val) => {
                      console.log('valll',val)
                      // const copyListData = JSON.parse(JSON.stringify(listData))
                      const copyListData = listData
                      copyListData.eq_sku_id = []
                      handleListInfoedit(copyListData)
                      this.setState({
                        modelValue: val,
                      })
                    }}
                    style={{minWidth: 120}}
                    >
                    {
                      normOption.length &&
                      normOption.map(item =>( 
                        <Option key={item.spu_id} value={item.spu_id}>{item.eq_model}</Option>
                      ))
                    }
                  </Select>
              </Form.Item>
            </Col>
            {/* <Col span={12}>
              <span>设备型号：</span>
              <Select onChange={this.setModeltype.bind(this)}  style={{ width: 120 }} >
                {set_list&&set_list.map((item,index)=>( 
                  <Option value={item.spu_id}>{item.eq_model}</Option>
                ))}
              </Select>
            </Col> */}
            <Col span={24}>
              {
                normOption[0] &&
                normOption[0].spec_info &&
                normOption[0].spec_info.length &&
                modelValue && 
                normOptionDom()
              }
            </Col>
          </Form>
        </Row>
      </Modal>
    )
  }
}